package com.accounting.client.frontend.customer.dialog;

import java.util.List;

import com.accounting.client.remote.Services;
import com.accounting.client.remote.obj.Customer;
import com.accounting.client.remote.obj.Product;
import com.accounting.client.remote.obj.PurchaseItem;
import com.accounting.client.remote.transfer.CreatePurchaseListRequest;
import com.accounting.client.resource.BoxResources;
import com.accounting.client.session.ErrorHandler;
import com.accounting.client.session.SessionManager;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.SplitLayoutPanel;
import com.google.gwt.user.client.ui.Widget;

import corelib.client.CollectionUtil;
import corelib.client.Util;
import corelib.client.delegate.CompleteCallback;
import corelib.client.delegate.Func1;
import corelib.client.linq.Linq;
import corelib.client.resource.CommonResources;
import corelib.client.schedule.DeferredTask;
import corelib.client.search.PagingRequest;
import corelib.client.search.PagingResult;
import corelib.client.ui.SimpleMask;
import corelib.client.ui.SimpleModal;
import corelib.client.ui.widget.ImageProvider;
import corelib.client.ui.widget.Size;
import corelib.client.ui.widget.WidgetListener;
import corelib.client.ui.widget.button.Button;
import corelib.client.ui.widget.dialog.SimpleLargeDialogHandler;
import corelib.client.ui.widget.form.ImageWidget;
import corelib.client.ui.widget.form.IntInputBox;
import corelib.client.ui.widget.form.SimpleLabel;
import corelib.client.ui.widget.form.fomatters.ValueFormatter;
import corelib.client.ui.widget.layout.LabelAlignment;
import corelib.client.ui.widget.layout.RelativeColumn;
import corelib.client.ui.widget.layout.RelativeLayout;
import corelib.client.ui.widget.layout.RelativeRow;
import corelib.client.ui.widget.messagebox.SimpleMessageBox;
import corelib.client.ui.widget.panel.SimpleLayoutPanel;
import corelib.client.ui.widget.panel.SimpleListPanel;
import corelib.client.ui.widget.toolbar.SimpleRibbon;

public class CustomerPurchaseListHandler extends SimpleLargeDialogHandler {
	
	private SimpleRibbon toolBar;
	private SimpleListPanel<Product> listPanel;
	private RelativeColumn purchaseItems;
	private final List<PurchaseItemRow> rows = CollectionUtil.newArrayList();
	private Customer customer;
	
	public CustomerPurchaseListHandler(Customer customer){
		this.customer = customer;
	}
	
	@Override
	public void onShowing() {
		super.onShowing();
		new DeferredTask().run(new ScheduledCommand(){
			@Override
			public void execute() {
				search(Util.EMPTY_STRING);
			}
		}, 400);
	}
	
	@Override
	public Widget getContentPanel() {
		toolBar = createToolBar();
		purchaseItems = new RelativeColumn();
		purchaseItems.setRowSpacing(12);
		listPanel = new SimpleListPanel<Product>(new WidgetListener() {
			@Override
			public void valueUpdated(Widget widget) {
				Product info = listPanel.getSelectedOption();
				if (info != null) {
					PurchaseItemRow row = new PurchaseItemRow(info.getCName(),rows);
					rows.add(row);
					purchaseItems.addRow(row);
				}
			}
		});
		listPanel.setIconProvider(new ImageProvider<Product>(){
			@Override
			public AbstractImagePrototype getImage(Product value) {
				return AbstractImagePrototype.create(BoxResources.INSTANCE.cube16());
			}
		});
		listPanel.setOptionFormatter(new ValueFormatter<Product>(){
			@Override
			public String format(Product value) {
				return value.getCName();
			}
		});
		
		ScrollPanel scrollPanel = new ScrollPanel();
		scrollPanel.getElement().getStyle().setPadding(15, Unit.PX);
		scrollPanel.add(purchaseItems.getPanel());
		
		SplitLayoutPanel splitLayout = new SplitLayoutPanel();
		splitLayout.addWest(listPanel, 200);
		splitLayout.add(scrollPanel);
		
		SimpleLayoutPanel layout = new SimpleLayoutPanel();
		layout.add(toolBar);
		layout.add(splitLayout);
		layout.setWidgetTopHeight(toolBar, 0, Unit.PX, 32, Unit.PX);
		layout.setWidgetTopBottom(splitLayout, 44, Unit.PX, 0, Unit.PX);
		return layout;
	}
	
	protected SimpleRibbon createToolBar(){
		SimpleRibbon toolBar = new SimpleRibbon();
		toolBar.getElement().getStyle().setPaddingTop(15, Unit.PX);
		Button send = new Button("发送购买清单", CommonResources.INSTANCE.accept16(), new WidgetListener(){
			@Override
			public void valueUpdated(Widget widget) {
				send();
			}
		});
		Button reset = new Button("重置", BoxResources.INSTANCE.delete16(), new WidgetListener(){
			@Override
			public void valueUpdated(Widget widget) {
				rows.clear();
				purchaseItems.clear();
				search(Util.EMPTY_STRING);
			}
		});
		reset.getElement().getStyle().setMarginLeft(10, Unit.PX);
		Button close = new Button("关闭", BoxResources.INSTANCE.delete16(), new WidgetListener(){
			@Override
			public void valueUpdated(Widget widget) {
				closeDialog();
			}
		});
		toolBar.addWidget(send);
		toolBar.addWidget(reset);
		toolBar.addWidget(close, Style.Float.RIGHT);
		return toolBar;
	}
	
	private void search(String keyword) {
		String passport = SessionManager.getPassport();
		PagingRequest request = new PagingRequest();
		request.setOffset(0);
		request.setLimit(1000);
		request.setKeyword(keyword);
		
		SimpleModal.show("搜索中...");
		Services.ProductService.ListProductsByKeyword(passport, request,
			new AsyncCallback<PagingResult<Product>>(){
				@Override
				public void onFailure(Throwable caught) {
					SimpleModal.hide();
					ErrorHandler.handleServiceError(caught);
				}
				@Override
				public void onSuccess(PagingResult<Product> result) {
					SimpleModal.hide();
					listPanel.setOptions(result.getData(), false);
				}
			}
		);
	}
	
	private List<PurchaseItem> getData() {
		return Linq.select(rows, new Func1<PurchaseItemRow, PurchaseItem>(){
			@Override
			public PurchaseItem run(PurchaseItemRow param) {
				return param.getItem();
			}
		});
	}
	
	private void send() {
		for (PurchaseItemRow row : rows) {
			if (row.validate() == Boolean.FALSE){
				return;
			}
		}
		
		List<PurchaseItem> data = getData();
		if (CollectionUtil.isEmpty(data)){
			SimpleMessageBox.error("错误", "请添加购买商品", CompleteCallback.Nil);
			return;
		}
		
		CreatePurchaseListRequest request = new CreatePurchaseListRequest();
		request.setPurchaseItems(getData());
		request.setCustomerId(customer.getId());
		
		SimpleMask.show(getDialog().asWidget(), "发送购买清单....");
		Services.CustomerService.SendPurchaseRequest(SessionManager.getPassport(), request,
			new AsyncCallback<Boolean>() {
				@Override
				public void onFailure(Throwable caught) {
					SimpleMask.hide(getDialog().asWidget());
					ErrorHandler.handleServiceError(caught);
				}
				@Override
				public void onSuccess(Boolean result) {
					SimpleMask.hide(getDialog().asWidget());
					if (result == Boolean.TRUE){
						closeDialog();
					}
				}
			}
		);
	}
	
	public class PurchaseItemRow extends RelativeRow {
		
		private SimpleLabel nameField;
		private IntInputBox countField;
		private ImageWidget closeButton;
		
		private String productName;
		private List<PurchaseItemRow> rows;
		
		public PurchaseItemRow(String productName, List<PurchaseItemRow> rows) {
			this.rows = rows;
			init(productName);
		}
		
		protected void init(String name) {
			int lw = 100;
			int fw = 100;
			nameField   = new SimpleLabel(name);
			countField  = new IntInputBox();
			closeButton = new ImageWidget(BoxResources.INSTANCE.delete16(), new Size(24,24), new WidgetListener(){
				@Override
				public void valueUpdated(Widget widget) {
					rows.remove(PurchaseItemRow.this);
					PurchaseItemRow.this.getWidget().removeFromParent();
				}
			});
			closeButton.getElement().getStyle().setMarginLeft(10, Unit.PX);
			
			add(new SimpleLabel(Util.EMPTY_STRING).setBold(true), 
				nameField.setBold(true),
				RelativeLayout.create(200, LabelAlignment.Top, lw)
			);
			add(new SimpleLabel("数量").setBold(true), 
				countField,
				RelativeLayout.create(fw, LabelAlignment.Top, lw)
			);
			add(new SimpleLabel(Util.EMPTY_STRING).setBold(true), 
				closeButton,
				RelativeLayout.create(24, LabelAlignment.Top, 24)
			);
		}
		
		public String getProductName() {
			return productName;
		}
		
		public boolean validate(){
			if (countField.getInteger() == null || countField.getInteger() == 0){
				countField.markError("购买数量不能为零");
				return false;
			}
			return true;
		}
		
		public PurchaseItem getItem() {
			PurchaseItem item = new PurchaseItem();
			item.setCount(countField.getInteger());
			item.setProductName(getProductName().trim());
			return item;
		}
		
	}
	
}
